# encoding: utf-8

# flake8: noqa

def build(bld):
    if not bld.env.BOOTLOADER:
        return

    if bld.env.EXT_FLASH_SIZE_MB:
        flashiface_lib = ['AP_HAL', 'AP_FlashIface', 'AP_HAL_Empty']
    else:
        flashiface_lib = []

    _build_dynamic_sources(bld)

    bld.ap_stlib(
        name= 'AP_Bootloader_libs',
        use=['dronecan'],
        dynamic_source='modules/DroneCAN/libcanard/dsdlc_generated/src/**.c',
        ap_vehicle='AP_Bootloader',
        ap_libraries= flashiface_lib + [
        'AP_Math',
        'AP_CheckFirmware',
        'AP_HAL',
        'AP_Networking',
        'AP_ROMFS',
        'AP_Common',
        ])

    # build external libcanard library
    bld.stlib(source='../../modules/DroneCAN/libcanard/canard.c',
              name='libcanard',
              use=['dronecan'],
              target='libcanard')

    bld.ap_program(
        use=['AP_Bootloader_libs', 'libcanard', 'dronecan'],
        program_groups='bootloader'
    )

def _build_dynamic_sources(bld):
    def write_version_header(tsk):
        bld = tsk.generator.bld
        return bld.write_version_header(tsk.outputs[0].abspath())

    bld(
        name='ap_version',
        target='ap_version.h',
        vars=['AP_VERSION_ITEMS'],
        rule=write_version_header,
    )

    bld.env.prepend_value('INCLUDES', [
        bld.bldnode.abspath(),
    ])
